/**
 * 给你一个字符串表达式 s ，请你实现一个基本计算器来计算并返回它的值。
 * 实现思路，使用栈
 * 一个栈保存操作符
 * 一个栈保存具体数字
 * @param {string} s
 * @return {number}
 */
var calculate = function(s) {
  let stack = [];
  let stackSign = [];
  let i = 0;
  let arr = s.replace(/\s+/g, '').match(/\(|\d+|-|\+|\)|\s/g);
  while(i<arr.length) {
    let code = arr[i];
    if(code === '(' || code === '+' || code === '-') {
      stackSign.push(code);
      console.log('遇到符号', stack, stackSign)
    } else if(!isNaN(code)) { // 遇到数字
      // 出栈，计算值后再入栈
      // 判断符号栈顶元素
      let top = stackSign[stackSign.length - 1];
      let sign;
      if(top === '+' || top === '-') {
        sign = stackSign.pop();
        console.log('栈顶元素', top, sign)
      }
      if(!sign) {
        stack.push(code);
      } else {
        // 出栈计算值后再入栈
        let precode = stack.pop();
        console.log(`${precode}${sign}${code}`)
        let result = eval(`${precode}${sign}${code}`);
        stack.push(result);
      }
      console.log('遇到数字', stack, stackSign)
    } else if(code === ')') {// 遇到反括号
      console.log('遇到反括号', stack, stackSign)
      // 将正括号出栈
      stackSign.pop();
      // 判断栈顶元素符号
      let top = stackSign[stackSign.length - 1];
      let nextcode;
      if(top === '+' || top === '-') {
        let precode = stack.pop();
        top = stackSign.pop();
        nextcode = stack.pop();
        stack.push(eval(`${precode}${top}${nextcode}`));
      }
    }
    i++;
  }
  console.log(stack[0])
  return stack[0]
};

// calculate("(1+(4+5+2)-3)+(6+8)")
// calculate("2-1 +2")
// calculate("-1 + 1")
calculate("(1+(3-9+(2+8)))")